<template>
  <div>
    <el-upload
      v-show="!isShowProcess"
      class="avatar-uploader"
      action="#"
      :limit="limit"
      :http-request="onRequest"
      :file-list="fileList"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :on-change="onChange"
      :on-exceed="onExceed"
      :before-upload="beforeAvatarUpload"
      accept="image/jpg,image/png"
      list-type="picture-card"
    >
      <i class="el-icon-plus avatar-uploader-icon" />
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>

    <el-progress v-if="isShowProcess" type="circle" :percentage="percentage" />

    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <img :src="imgUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDgCRYPzIK6bqoVv4vXeU3LN7amiNkqjMj', // 身份识别 ID
  SecretKey: '7xXqsd8MJzPXOyGI3WidIgneEWXGjvpS' // 身份密钥
})
console.log(cos)
export default {
  props: {
    limit: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      imgUrl: '',
      isShowProcess: false,
      percentage: 0
    }
  },

  created() {},

  methods: {
    onRequest(data) {
      this.isShowProcess = true
      // console.log(data.file)
      this.id = setInterval(() => {
        if (this.percentage < 97) {
          this.percentage++
        } else {
          clearInterval(this.id)
          this.percentage = 99
        }
      }, 500)
      cos.putObject({
        Bucket: 'hrsaas24-1308960786', /* 填入您自己的存储桶，必须字段 */
        Region: 'ap-nanjing', /* 存储桶所在地域，例如ap-beijing，必须字段 */
        Key: data.file.name, /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
        StorageClass: 'STANDARD',
        Body: data.file, // 上传文件对象
        onProgress: progressData => {
          if (progressData.percent === 1) {
            this.percentage = 100
            setTimeout(() => {
              this.isShowProcess = false
              this.percentage = 0
            }, 500)
          }
        }
      }, (err, data) => {
        console.log(err || data)
        if (err) {
          this.isShowProcess = true
          this.$message.error('网络错误，上传失败')
          this.fileList.splice(this.fileList.length - 1, 1)
        }
        if (!err && data.statusCode === 200) {
          this.$message.success('上传成功')
          const fileLength = this.fileList.length - 1
          this.fileList[fileLength].url = 'https://' + data.Location
          this.$emit('on-success', this.fileList)
        }
      })
    },
    onPreview(file) {
      console.log(file)
      this.imgUrl = file.url
      this.dialogVisible = true
    },
    onRemove(file, fileList) {
      this.fileList = fileList // 参数fileList是已经删除过的返回数据
    },
    beforeAvatarUpload(file) {
      const imgType = ['image/gif', 'image/jpg']
      if (!imgType.includes(file.type)) {
        this.$message.error('请上传正确格式的图片')
        return false
      }
      const maxSize = 1 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('请上传1M以内的图片')
        return false
      }
    },
    onChange(file, fileList) {
      this.isShowProcess = true
      this.fileList = fileList
    },
    onExceed() {
      this.$message.error('最多只能上传' + this.limit + '图片')
    }
  }
}
</script>

<style lang="scss">
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 148px;
  height: 148px;
  line-height: 148px;
  text-align: center;
}
.avatar {
  width: 148px;
  height: 148px;
  display: block;
}
</style>
